package cn.wolfcode.wolf2w.redis.service.impl;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.exception.LogicException;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.redis.util.RedisKeys;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserInfoRedisServiceImpl implements IUserInfoRedisService{
    @Autowired
    private StringRedisTemplate template;

    @Override
    public void setVerifyCode(String phone, String code) {
        template.opsForValue().set(RedisKeys.VERIFY_CODE.join(phone), code, RedisKeys.VERIFY_CODE.getTimeout(), TimeUnit.SECONDS);
    }

    @Override
    public String getVerifyCode(String phone) {
        String code = template.opsForValue().get(RedisKeys.VERIFY_CODE.join(phone));
        return code;
    }

    @Override
    public String setToken(UserInfo user) {
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        String key=RedisKeys.USER_LOGIN.join(token);
        //保存到缓存
        template.opsForValue().set(key, JSON.toJSONString(user),RedisKeys.USER_LOGIN.getTimeout(),TimeUnit.SECONDS);
        //返回令牌token
        return token;
    }

    @Override
    public UserInfo checkUser(String token) {
        //拼接key
        String key = RedisKeys.USER_LOGIN.join(token);
        String s = template.opsForValue().get(key);
        UserInfo userInfo = JSON.parseObject(s, UserInfo.class);
        if (userInfo==null){
            throw new LogicException("请先登录");
        }
        //将时间延长30分钟
        template.opsForValue().set(key, s,RedisKeys.USER_LOGIN.getTimeout(),TimeUnit.SECONDS);
        return userInfo;
    }
    @Override
    public void checkLimit(String phone) {
        //组装key
        String key="limit:"+phone;
        //先查询
        String s = template.opsForValue().get(key);
        if (s==null){
            //如果没有限制,则加上限制
            template.opsForValue().set(key, "2", 60l, TimeUnit.SECONDS);
        }else {
            //如果有限制,则限制减一
            int time=Integer.valueOf(s)-1;
            //如果减一后次数小于等于0抛异常
            if (time<=0){
                //抛异常
                throw new LogicException("发送验证码过于频繁");
            }else {
                //没有小于等于0,则偏移1
                template.opsForValue().decrement(key);
            }
        }
    }
}
